import axios from 'axios';
import Qs from 'qs';
import {
	Message
} from 'element-ui';



const service = axios.create({
	timeout: 30 * 1000, // 请求超时时间
	withCredentials: true,
	// headers:{
	//     'Content-Type': 'application/json'
	// },
	// baseURL:'/zgq-epana-nucleate'
	headers: {
		// 'Content-Type': 'application/json;charset=utf-8'
		'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
	},
})

// service.defaults.baseURL = '/lnexamtest';
service.defaults.baseURL = '/zgq-epana-nucleate';

//http request 拦截器
service.interceptors.request.use(
	config => {
		if (config.headers['Content-Type'].indexOf('x-www-form-urlencoded') > -1 && config.method.toLocaleLowerCase() === 'post') {
			config.data = Qs.stringify(config.data)
		}
		if (config.needAuth) {
			config.headers['accessToken'] = localStorage.getItem('access_token')
		} else {
			config.headers['accessToken'] = ''
		}
		return config;
	},
	error => {
		Message({
			message: '系统错误',
			duration: 2000,
		});
		return Promise.reject(error);
	}
);


//http response 拦截器
service.interceptors.response.use(
	response => {
		if (response.data.code != 200 && !response.config.noToast && response.data.code != 401 && response.data.code != 403 && response.data.msg == '请登录') {
			Message.close();
			Message({
				message: response.data.msg,
				duration: 3000,
			});
		} else if (response.data.code == 403 || response.data.code == 401 || response.data.msg == '请登录') {
			Message.close();
			Message({
				message: '登录失效,请重新登录...',
				duration: 1500,
			});
			setTimeout(() => {
				//   window.location.replace('http://111.75.240.74:56794/zgq-epana-nucleate/login')
			}, 1000);
			if (!response.config.noLogin) {
				console.log('重新登录')
			}
		}
		return Promise.resolve(response.data)
	},
	error => {
		if (error.message.includes('timeout')) { // 判断请求异常信息中是否含有超时timeout字符串
			Message.close();
			// router.push('/home')
			Message({
				message: '网络超时',
				duration: 2000,
			});
			return Promise.reject(error); // reject这个错误信息
		}
		return Promise.reject(error)
	}
)

export default service